package cc.linker.steplink.crm.merchant.controller;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.model.FormLoginDto;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.oss.OssService;
import cc.linker.steplink.crm.commons.utils.CharUtils;
import cc.linker.steplink.crm.commons.utils.CopyMap;
import cc.linker.steplink.crm.merchant.pojo.Sku;
import cc.linker.steplink.crm.merchant.service.mall.MallsService;
import cc.linker.steplink.crm.merchant.util.ExcelDataUtil;
import cc.linker.steplink.crm.merchanth5.commons.FormFilter;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.dao.acs.MerchantInfoDao;
import cc.linker.steplink.crm.merchant.pojo.ShopGoods;
import cc.linker.steplink.crm.merchant.pojo.SpecKey;
import cc.linker.steplink.crm.merchant.pojo.SpecValue;
import cc.linker.steplink.crm.merchant.service.NewMallService;
import cc.linker.steplink.crm.merchant.service.ShopGoodsService;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchanth5.pojo.integral.IntegralGoodsPo;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchant.service.IsLossGoodsService;
import cc.linker.steplink.crm.merchanth5.service.redis.GoodsService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.parse;

@RestController
@RequestMapping("/shop/goods")
public class ShopGoodsController {

    private static final String uploadFirstSubDir = "goods";
    @Autowired
    private ShopGoodsService shopGoodsService;
    @Autowired
    private OssService ossService;
    @Autowired
    private NewMallService newMallService;
    @Autowired
    private MallService mallService;
    @Autowired
    private MerchantInfoDao merchantInfoDao;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private IsLossGoodsService isLossGoodsService;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private MallsService mallsService;
    @Autowired
    private FormFilter formFilter;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GoodsService goodsService;

    /**
    * @Description：获取商品列表
    * @DateTime：2020/10/16 8:25
    * @Params：
    * @Return：
    */
    @PostMapping("/list")
    public Object getGoodsList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userInfo.getOrgId());
        return newMallService.getGoodsList(params);
    }

    /**
    * @Description：获取商品列表
    * @DateTime：2020/10/16 8:25
    * @Params：
    * @Return：
    */
    @GetMapping("/excelList")
    public void excelList(String key,Integer status,Integer goodsType ,String group, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> params = new HashMap<>();
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userInfo.getOrgId());
        if(userInfo.getSaler()){
            params.put("adminId", userInfo.getCustomerId());
        }
        if (!StringUtils.isEmpty(key)) {
            key = URLDecoder.decode(key.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            key = key.replaceAll("%", "/%");
        }
        params.put("key",key);
        params.put("status",status);
        params.put("type",goodsType);
        if(!StringUtils.isEmpty(group)){
            String StringType=group;
            List<String> StringResult = Arrays.asList(StringType.split(",")).stream().map(s ->s.trim()).collect(Collectors.toList());
            params.put("group",StringResult);
        }

        newMallService.excelList(params,userInfo.getOrgId(),response);
    }

    /**
     * 给编辑器用的接口，商品列表
     *
     * @param orgId     机构id
     * @param pageIndex 页码
     * @param pageSize  页面大小
     * @param key       商品关键字
     * @param group     商品分组id
     * @param userId    用户cas_id
     */
    @PostMapping("/listPaging")
    public Object listPaging(@RequestBody Map<String, Object> params) throws GlobalException, UnsupportedEncodingException {
        return newMallService.listPaging(params);
    }

    /**
     * 商品上下架
     *
     * @param goodsId 商品id
     * @param mine    商品类型0-自有1-联盟2-共享
     */
    @PostMapping("/updateStatus")
    public void updateStatus(@RequestBody Map<String, Object> params, HttpServletRequest request) throws GlobalException {

        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        if(null == params.get("param")){
            throw GlobalException.build("至少选择一个商品");
        }
        List<Map<String, Object>> param = (List<Map<String, Object>>)params.get("param");
        for(Map<String, Object> pa:param){
            pa.put("orgId",userInfo.getOrgId());
            newMallService.changeGoodStatus(pa, (int)pa.get("mine"));
        }
    }

    /**
     * 更改排序
     *
     * @param goodsId 商品id
     * @param sort    更改后的排序
     */
    @PostMapping("/updateSort")
    public void updateSort(@RequestBody Map<String, Object> params, HttpServletRequest request) throws GlobalException {
        if(StringUtils.isEmpty(params.get("goodsId")) || StringUtils.isEmpty(params.get("sort")) ){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean isSaler = userinfo.getSaler();
        params.put("isSaler",isSaler);
        newMallService.updateSort(params);
    }

    /**
     * 商品新增编辑
     *
     * @param goodsBanner      商品图片(数组)
     * @param goodsContent     商品简介
     * @param goodsCount       商品数量
     * @param goodsCover       商品封面
     * @param goodsFreight     运费
     * @param goodsGroup       商品分组
     * @param goodsId          商品id,编辑时传
     * @param goodsName        商品名
     * @param goodsSpec        规格
     * @param goodsStatus      商品状态
     * @param isFreight        是否包邮
     * @param moneyAmount      价格
     * @param originalCost     原价
     * @param sku              规格值
     * @param labels           标签
     * @param classificationId 类目id
     * @param videoContent     视频内容
     * @param videoCover       视频封面
     * @param videoResId       视频资源id
     * @param shareTitle       分享标题
     * @param shareInfo        分享简介
     * @param quota            是否限购0-不限 1-限制
     * @param quotaCycle       限购周期0-终身，1-日，2-周，3-月，4-近x天
     * @param quotaNum         限购件数
     * @param quotaDay         限购天数
     *
     *                         1.12.2 版本新增
     * @param malls            供货商品 供货商品-1 平台商品-0
     * @param mallsAmountMin   建议零售价最小值
     * @param mallsAmountMax   建议零售价最大值
     */
    @PostMapping("/save")
    public void save(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userInfo.getOrgId());
        params.put("adminId", userInfo.getAdminId());
        if(userInfo.getSaler()){
            params.put("customerId", userInfo.getCustomerId());
        }
        //判断亏损
        boolean ifMalls = !StringUtils.isEmpty(params.get("malls")) && "1".equals(params.get("malls").toString());
        if(!ifMalls){
            this.checkGoodsRewetting(params,request);
        }
        if(null!=params.get("goodsRemark")){
            params.put("goodsRemark", JSON.toJSONString(params.get("goodsRemark")));
        }
        newMallService.save(params);
    }

    /**
     * 判断是否亏损提示
     * @param params
     * @param session
     */
    @PostMapping("/checkgoodsrewetting")
    public void checkGoodsRewetting(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        params.put("adminId",  userinfo.getAdminId());
        Long goodsId = -1L;
        if(!StringUtils.isEmpty(params.get("goodsId"))){
            goodsId = Long.parseLong(params.get("goodsId").toString());
        }
        params.put("goodsId", goodsId);
        //根据商品id获取优惠券列表
        List<Map<String, Object>> couponList = isLossGoodsService.getCouponListByGoodsId(userinfo,goodsId);
        if(couponList.size()>0){
            Map capyMap = new HashMap();
            CopyMap.mapCopy(params,capyMap);
            capyMap = this.toSku(capyMap);
            for (Map<String, Object> couponInfo : couponList){
                //销售金额和会员价减去优惠金额
                capyMap = isLossGoodsService.reduceGoodsInfoByMap(capyMap,couponInfo);
                if(!StringUtils.isEmpty(capyMap.get("isFreeFreight")) && "1".equals(capyMap.get("isFreeFreight").toString())){
                    capyMap.remove("isFreight");
                }
                newMallService.checkGoodsRewetting(capyMap);
            }
        }else {
            newMallService.checkGoodsRewetting(params);
        }

    }

    public Map toSku(Map capyMap){
        List<Sku> newSku = new ArrayList<>();
        List<Map> sku = (List<Map>) capyMap.get("sku");
        if(sku!=null && sku.size()>0){
            for(Map skuMap: sku){
                try{
                    if(!StringUtils.isEmpty(skuMap.get("skuId"))){
                        skuMap.put("skuId",Long.valueOf(skuMap.get("skuId").toString()));
                    }
                    if(!StringUtils.isEmpty(skuMap.get("mallsSkuId"))){
                        skuMap.put("mallsSkuId",Long.valueOf(skuMap.get("mallsSkuId").toString()));
                    }
                    if(!StringUtils.isEmpty(skuMap.get("goodsId"))){
                        skuMap.put("goodsId",Long.valueOf(skuMap.get("goodsId").toString()));
                    }
                    if(!StringUtils.isEmpty(skuMap.get("moneyAmount"))){
                        skuMap.put("moneyAmount",Double.valueOf(skuMap.get("moneyAmount").toString()));
                    }
                    if(!StringUtils.isEmpty(skuMap.get("mallsAmount"))){
                        skuMap.put("mallsAmount",Double.valueOf(skuMap.get("mallsAmount").toString()));
                    }else {
                        skuMap.remove("mallsAmount");
                    }
                    if(!StringUtils.isEmpty(skuMap.get("goodsCount"))){
                        skuMap.put("goodsCount",Long.valueOf(skuMap.get("goodsCount").toString()));
                    }else {
                        skuMap.remove("goodsCount");
                    }
                    if(!StringUtils.isEmpty(skuMap.get("memberAmount"))){
                        skuMap.put("memberAmount",Double.valueOf(skuMap.get("memberAmount").toString()));
                    }else {
                        skuMap.remove("memberAmount");
                    }
                    if(!StringUtils.isEmpty(skuMap.get("mallsAmountMin"))){
                        skuMap.put("mallsAmountMin",Double.valueOf(skuMap.get("mallsAmountMin").toString()));
                    }else {
                        skuMap.remove("mallsAmountMin");
                    }
                    if(!StringUtils.isEmpty(skuMap.get("mallsAmountMax"))){
                        skuMap.put("mallsAmountMax",Double.valueOf(skuMap.get("mallsAmountMax").toString()));
                    }else {
                        skuMap.remove("mallsAmountMax");
                    }
                    if(!StringUtils.isEmpty(skuMap.get("originalCost"))){
                        skuMap.put("originalCost",Double.valueOf(skuMap.get("originalCost").toString()));
                    }else {
                        skuMap.remove("originalCost");
                    }
                    if(!StringUtils.isEmpty(skuMap.get("originalPrice"))){
                        skuMap.put("originalPrice",Double.valueOf(skuMap.get("originalPrice").toString()));
                    }else {
                        skuMap.remove("originalPrice");
                    }
                    Sku newSkuBean = BeanMapUtils.mapToBean(skuMap,Sku.class);
                    newSku.add(newSkuBean);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            capyMap.put("sku",newSku);
        }
        return capyMap;
    }
    /**
     * 删除商品
     *
     * @param goodsIds 商品id
     * @param mine     商品类型0-自有1-联盟2-共享
     */
    @PostMapping("/delete")
    public void delete(@RequestBody Map<String, Object> params, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);

        if(null == params.get("param")){
            throw GlobalException.build("至少选择一个商品");
        }
        List<Map<String, Object>> param = (List<Map<String, Object>>)params.get("param");
        for(Map<String, Object> pa:param){
            Long[] goodsIds = {Long.valueOf(pa.get("goodsId").toString())};
            int mine = Integer.parseInt(pa.get("mine").toString());
            shopGoodsService.delete(goodsIds, userinfo.getAdminId(), userinfo.getOrgId(), mine, userinfo.getSaler());
        }
//        shopGoodsService.delete(goodsIds, adminId, orgId, mine, ifSales);
    }

    /**
     * 上传商品图片
     */
    @PostMapping("/uploadPicture")
    public Object uploadPicture(MultipartFile file) {
        String url = ossService.uploadLocalFileToOss(uploadFirstSubDir, "StepLink", file);
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);
        return map;
    }

    /**
     * 保存规格
     *
     * @param specKeyName 规格名
     * @return 规格id
     */
    @GetMapping("/saveSpecKey")
    public Object saveSpecKey(String specKeyName, HttpServletRequest request) throws GlobalException {
        if (StringUtils.isEmpty(specKeyName)) {
            throw new GlobalException(new ResponseException(400, "规格名不能为空"));
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        SpecKey specKey = new SpecKey();
        specKey.setSpecKeyName(specKeyName);
        specKey.setOrgId( userinfo.getOrgId());
        //获取规格id
        Long specKeyId = shopGoodsService.getSpecKeyId(specKey);
        if (specKeyId == null) {
            shopGoodsService.saveSpecKey(specKey);
            specKeyId = specKey.getSpecKeyId();
        }
        return specKeyId;
    }

    /**
     * 保存规格值
     *
     * @param specKeyId     规格id
     * @param specValueName 规格值名
     * @return 规格值id
     */
    @GetMapping("/saveSpecValue")
    public Object saveSpecValue(Long specKeyId, String specValueName) throws GlobalException {
        if (specKeyId == null || StringUtils.isEmpty(specValueName)) {
            throw new GlobalException(new ResponseException(400, "参数不能为空"));
        }
        SpecValue specValue = new SpecValue();
        specValue.setSpecValueName(specValueName);
        specValue.setSpecKeyId(specKeyId);
        //获取规格值id
        Long specValueId = shopGoodsService.getSpecValueId(specValue);
        if (specValueId == null) {
            shopGoodsService.saveSpecValue(specValue);
            specValueId = specValue.getSpecValueId();
        }
        return specValueId;
    }


    /**
     * 获取规格列表
     */
    @GetMapping("/specKeyList")
    public Object specKeyList(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", userinfo.getOrgId());
        return shopGoodsService.specKeyList(params);
    }

    /**
     * 获取规格下规格值列表
     *
     * @param specKeyId 规格id
     */
    @GetMapping("/specValueList")
    public Object specValueList(Long specKeyId) throws GlobalException {
        return shopGoodsService.specValueList(specKeyId);
    }

    /**
     * 获取商品详情
     *
     * @param goodsId 商品id
     */
    @GetMapping("/getGoods")
    public Object getGoods(Long goodsId) throws GlobalException {
        return shopGoodsService.getGoods(goodsId);
    }

    @GetMapping("/getGoodsById")
    public Map getGoodsById(Long goodsId) throws GlobalException {
        return goodsService.getGoodsInfo(goodsId.toString());
    }

    @GetMapping("/getIntegralGoodsById")
    public IntegralGoodsPo getIntegralGoods(Long goodsId){
        return goodsService.getIntegralGoodsInfo(goodsId);
    }

    @GetMapping("/getGoodsByIds")
    public List<Map> getGoodsByIds(String goodsIds) throws GlobalException {
        return goodsService.getGoodsByIds(goodsIds);
    }


    @GetMapping("/getIntegralGoodsByIds")
    public List<IntegralGoodsPo> getIntegralGoodsByIds(String goodsIds){
        return goodsService.getIntegralGoodsByIds(goodsIds);
    }

    /**
     * 商品关联文章
     *goodsService.getGoodsInfo
     * @param params
     * @param session
     */
    @PostMapping("/bindArticle")
    public void bindArticle(@RequestBody Map<String, Object> params,HttpServletRequest request)
            throws GlobalException {
        if (params == null || params.isEmpty()) {
            throw GlobalException.build("非法参数");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        String salerId = newMallService.getSalerId(userinfo.getAdminId());
        if (!StringUtils.isEmpty(salerId)) {
            params.put("salerId", salerId);
        } else {
            throw GlobalException.build("此商品无法关联文章");
        }
        shopGoodsService.updateGoodsBindArticle(params);
        shopGoodsService.cleanGoodsBindArticle(params);
    }


    /**
    * @Description：封禁商品
    * @DateTime：2020/10/16 8:31
    * @Params：
    * @Return：
    */
    @PostMapping("/banned")
    public void banned(@RequestBody Map<String, Object> params,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        shopGoodsService.banned(params);
    }

    /**
     * 联盟/我的商品列表
     *
     * @param pageIndex 页码
     * @param pageSize  页面大小
     * @param goodsName 商品名称
     * @param goodsType 商品类型1-商品3-知识付费
     * @param merchant  联盟商家名称
     * @param phone     联盟商家联系方式
     * @param mine      0-联盟1-我的
     * @param groupId   分组id
     */
    @PostMapping("/allianceMallList")
    public PageInfo allianceMallList(@RequestBody Map<String, Object> params,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        params.put("ifSales", userinfo.getSaler());
        params.put("adminId", userinfo.getAdminId());
        return shopGoodsService.allianceMallList(params);
    }

    /**
     * 联盟共享库商品列表
     *
     * @param pageIndex 页码
     * @param pageSize  页面大小
     * @param goodsName 商品名称
     * @param goodsType 商品类型1-商品 2表单 3-知识付费
     * @param merchant  联盟商家名称
     * @param phone     联盟商家联系方式
     */
    @PostMapping("/allianceShareList")
    public PageInfo allianceShareList(@RequestBody Map<String, Object> params,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        params.put("ifSales", userinfo.getSaler());
        params.put("adminId", userinfo.getAdminId());
        return shopGoodsService.allianceShareList(params);
    }

    /**
     * 添加/移除至(从)商城
     *
     * @param goodsId 商品id
     * @param groupId 分组id
     */
    @PostMapping("/addToMall")
    public void addToMall(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if(userinfo.getSaler()){
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            params.put("customerId", customerId);
        }
        params.put("orgId", userinfo.getOrgId());
        shopGoodsService.addToMall(params);
    }


    /**
     * (取消)参与推广/设置返润
     *
     * @param goodsId   商品id
     * @param rebate    返润比例
     * @param promotion 是否推广?0:1
     */
    @PostMapping("/promotion")
    public void promotion(@RequestBody Map<String, Object> params,  HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        shopGoodsService.promotion(params, userinfo);
    }


    /**
     * 判断 返润设置是否亏损 提示
     */
    @PostMapping("/checkpromotion")
    public void checkPromotion(@RequestBody Map<String, Object> params,  HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (params.get("goodsId") == null) {
            throw GlobalException.build("缺少参数");
        }
        Long goodsId =Long.valueOf(params.get("goodsId").toString());
        String promotion = String.valueOf(params.get("promotion"));
        if ("1".equals(promotion)) {
            //有反润，判断亏损
            //没反润创建商品时或者之前有反润时就已经判断过
            ShopGoods goods = shopGoodsService.getGoods(goodsId);
            Map goodsMap = BeanMapUtils.beanToMap(goods);
            List<Map<String, Object>> couponList = isLossGoodsService.getCouponListByGoodsId(userinfo,goodsId);
            if(couponList.size()>0){
                Map capyMap = new HashMap();
                CopyMap.mapCopy(goodsMap,capyMap);
                for (Map<String, Object> couponInfo : couponList){
                    //销售金额和会员价减去优惠金额
                    capyMap = isLossGoodsService.reduceGoodsInfoByMap(capyMap,couponInfo);
                    ShopGoods copyGoods = null;
                    try {
                         copyGoods = BeanMapUtils.mapToBean(capyMap,ShopGoods.class);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    shopGoodsService.checkPromotion(params, copyGoods);
                }
            }else {
                shopGoodsService.checkPromotion(params, goods);
            }

        }
    }

    /**
     * 判断 返润设置是否亏损 提示
     */
    @PostMapping("/checkStatus")
    public void checkStatus(@RequestBody Map<String, Object> params,  HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (params.get("goodsId") == null) {
            throw GlobalException.build("缺少参数");
        }
        Long goodsId =Long.valueOf(params.get("goodsId").toString());

        //有反润，判断亏损
        //没反润创建商品时或者之前有反润时就已经判断过
        ShopGoods goods = shopGoodsService.getGoods(goodsId);
        params.put("rebate",goods.getRebate()==null?"0":goods.getRebate());
        Map goodsMap = BeanMapUtils.beanToMap(goods);
        List<Map<String, Object>> couponList = isLossGoodsService.getCouponListByGoodsId(userinfo,goodsId);
        if(couponList.size()>0){
            Map capyMap = new HashMap();
            CopyMap.mapCopy(goodsMap,capyMap);
            for (Map<String, Object> couponInfo : couponList){
                //销售金额和会员价减去优惠金额
                capyMap = isLossGoodsService.reduceGoodsInfoByMap(capyMap,couponInfo);
                ShopGoods copyGoods = null;
                try {
                    copyGoods = BeanMapUtils.mapToBean(capyMap,ShopGoods.class);
                }catch (Exception e){
                    e.printStackTrace();
                }
                shopGoodsService.checkPromotion(params, copyGoods);
            }
        }else {
            shopGoodsService.checkPromotion(params, goods);
        }

    }

    /**
     * 判断 返润设置是否亏损 提示
     */
    @PostMapping("/checkStatusByTemplate")
    public void checkStatusByTemplate(@RequestBody Map<String, Object> params,  HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (params.get("templateId") == null) {
            throw GlobalException.build("缺少参数");
        }
        String templateId = params.get("templateId").toString();
        List<Long> goodsIds = shopGoodsService.getGoodsIdsByTemplateId(templateId);
        for(Long goodsId : goodsIds){
//            Long goodsId =Long.valueOf(params.get("goodsId").toString());
            //有反润，判断亏损
            //没反润创建商品时或者之前有反润时就已经判断过
            ShopGoods goods = shopGoodsService.getGoods(goodsId);
            params.put("rebate",goods.getRebate()==null?"0":goods.getRebate());
            Map goodsMap = BeanMapUtils.beanToMap(goods);
            if(goods.getMalls()!=null && goods.getMalls()==1){
                goodsMap.put("minGoodsFreight",params.get("minGoodsFreight"));
                mallsService.checkGoodsRewetting(goodsMap);
                continue;
            }
            List<Map<String, Object>> couponList = isLossGoodsService.getCouponListByGoodsIdTemplate(userinfo,goodsId);
            if(couponList.size()>0){
                Map capyMap = new HashMap();
                CopyMap.mapCopy(goodsMap,capyMap);
                for (Map<String, Object> couponInfo : couponList){
                    //销售金额和会员价减去优惠金额
                    capyMap = isLossGoodsService.reduceGoodsInfoByMap(capyMap,couponInfo);
                    ShopGoods copyGoods = null;
                    try {
                        copyGoods = BeanMapUtils.mapToBean(capyMap,ShopGoods.class);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    shopGoodsService.checkPromotion(params, copyGoods);
                }
            }else {
                shopGoodsService.checkPromotion(params, goods);
            }
        }
    }

    /**
     * 商品推广-我的商品和共享商品
     *
     * @param pageIndex 页码
     * @param pageSize  页大小
     * @param shared    分享状态0-未共享1-已共享
     * @param key       搜索关键字
     * @param mine      我的0-我的1-全部
     * @param orgId     机构id
     * @param choose    选用状态0-未选用1-选用
     */
    @PostMapping("/productPromotion")
    public PageInfo productPromotion(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String reqOrgId = (String) params.get("orgId");
        params.put("reqOrgId", reqOrgId);
        params.put("orgId", userinfo.getOrgId());
        Boolean ifSales = userinfo.getSaler();
        if (ifSales) {
            params.put("adminId", userinfo.getAdminId());
            return shopGoodsService.productPromotionForSaler(params);
        } else {
            return shopGoodsService.productPromotion(params);
        }
    }

    /**
     * 商品设置共享及返润比例
     *
     * @param goodsId 商品id
     * @param rebate  返润比例
     * @param shared  是否共享
     */
    @PostMapping("/productShared")
    public void productShared(@RequestBody Map<String, Object> params) {
        shopGoodsService.productShared(params);
    }

    /**
     * 商品设置共享及返润比例(给内容库用的接口)
     *
     * @param goodsId 商品id(多个用逗号拼接)
     * @param rebate  返润比例
     * @param shared  是否共享
     */
    @PostMapping("/mediaProductShared")
    public void mediaProductShared(@RequestBody Map<String, Object> params) {
        shopGoodsService.mediaProductShared(params);
    }

    /**
     * 商品设置选用(给内容库用的接口)
     *
     * @param goodsId 商品id(多个用逗号拼接)
     * @param orgId   机构id
     */
    @PostMapping("/mediaProductChoose")
    public void mediaProductChoose(@RequestBody Map<String, Object> params) {
        shopGoodsService.mediaProductChoose(params);
    }

    /**
     * 共享商品选用/取消选用
     *
     * @param goodsId 商品id
     */
    @PostMapping("/productChoose")
    public void productChoose(@RequestBody Map<String, Object> params,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        if (userinfo.getSaler()) {
            String customerId = merchantInfoDao.getCustomerIdByAdminId(userinfo.getAdminId());
            params.put("orgId", customerId);
        }
        shopGoodsService.productChoose(params);
    }

    /**
     * 共享商品-商品来源：机构信息列表
     */
    @GetMapping("/orgInfoList")
    public List<Map<String, Object>> orgInfoList() {
        return shopGoodsService.orgInfoList();
    }

    /**
     * 查看选用
     *
     * @param goodsId
     */
    @PostMapping("/viewChoose")
    public List<Map<String, Object>> viewChoose(@RequestBody Map<String, Object> params) {
        return shopGoodsService.getViewChoose(params);
    }

    /**
     * 判断认证信息是否完整
     *
     * @param session
     * @return
     */
    @GetMapping("/checkmerInfo")
    public Map checkMerInfo(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map params = new HashMap();
        params.put("orgId", userinfo.getOrgId());
        params.put("ifSales", userinfo.getSaler());
        params.put("adminId", userinfo.getAdminId());

        Boolean ifComplete = newMallService.checkMerInfo(params);
        Map temps = new HashMap();
        temps.put("ifComplete", ifComplete);
        return temps;
    }

    /**
     * 清除商品缓存
     *
     */
    @PostMapping("/flushGoodsCache")
    public void flushGoodsCache(@RequestBody Map<String, Object> params){
        if(params==null || StringUtils.isEmpty(params.get("goodsId"))){
            throw GlobalException.build("缺少参数！");
        }
        Long goodsId = Long.valueOf(params.get("goodsId").toString());
        mallService.flushCartGoodsSkuInfo(goodsId);
    }


    /**
     * 获取商品服务列表
     * @param pageIndex
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/getgoodsservicelist")
    public PageInfo getGoodsServiceList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                        @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                        HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        Map<String,Object> param = new HashMap<>();
        param.put("orgId",orgId);
        if (userinfo.getSaler()) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        param.put("createUserId", customerId);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(shopGoodsService.getGoodsServiceList(param));
    }

    /**
     * 获取商品服务全部列表
     * @param pageIndex
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/getAllGoodsServiceList")
    public List<Map<String,Object>> getAllGoodsServiceList(String serviceIds,HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        Map<String,Object> param = new HashMap<>();
        param.put("orgId",orgId);
        param.put("serviceIds",serviceIds);
        if (userinfo.getSaler()) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        param.put("createUserId", customerId);
        return shopGoodsService.getAllGoodsServiceList(param);
    }

    /**
     * 新增、编辑商品服务
     * @param request
     * @param param
     */
    @PostMapping("/savegoodsservice")
    public void saveGoodsService(HttpServletRequest request,@RequestBody Map<String, Object> param){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        param.put("orgId",orgId);
        if (userinfo.getSaler()) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        param.put("createUserId", customerId);
        shopGoodsService.saveGoodsService(param);
    }

    @PostMapping("/delgoodsservice")
    public void delGoodsService(HttpServletRequest request,@RequestBody Map<String, Object> param){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        param.put("orgId",orgId);
        if (userinfo.getSaler()) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        param.put("createUserId", customerId);
        shopGoodsService.delGoodsService(param);
    }


    @GetMapping("/getgoodsserviceinfo")
    public Map<String,Object> getGoodsServiceInfo(HttpServletRequest request,Integer id){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return shopGoodsService.getGoodsServiceInfo(id);
    }


    /**
     * 我的共享-商品
     * @param pageIndex
     * @param pageSize
     * @param type
     * @param name
     * @param request
     * @return
     */
    @GetMapping("/getmysharegoodslist")
    public PageInfo getMyShareGoodsList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                        @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                        @RequestParam(value = "type", defaultValue = "1") Integer type,
                                        @RequestParam(value = "name", defaultValue = "") String name,
                                        HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String,Object> param = new HashMap<>();
        param.put("orgId",orgId);
        param.put("type",type);
        if(!StringUtils.isEmpty(name)){
            param.put("goodsName", CharUtils.escapeQueryChars(name));
        }
        if (userinfo.getSaler()) {
            //小b查看只展示自己的商品
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("belongId", customerId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(shopGoodsService.getMyShareGoodsList(param));
    }

    /**
     * 共享、取消共享
     * @param request
     * @param param
     */
    @PostMapping("/savesharing")
    public void saveSharing(HttpServletRequest request,@RequestBody Map<String, Object> param){
        FormLoginDto formLoginDto = formFilter.getFormLoginDto(request, false);
        param.put("formLoginDto",formLoginDto);
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        param.put("orgId",orgId);
        if (userinfo.getSaler()) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("createUserId", customerId);
        }
        shopGoodsService.saveSharing(param);
    }

    /**
     * 导入修改商品列表
     * @param request
     * @param file
     */
    @PostMapping(value = "/importExcelData")
    @ResponseBody
    public Map importExcelData(MultipartFile file,HttpServletRequest request){
        List<Map<String,String>> list;
        try{
            list = ExcelDataUtil.getAllByExcel(file);
        }catch (Exception e){
            e.printStackTrace();
            throw GlobalException.build("导入表格格式错误，与导入模板不符");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String adminId = "";
        if(userinfo.getSaler()){
            adminId = userinfo.getCustomerId();
        }
        List<Map<String,String>> ableList = new ArrayList<>();
        List<Map<String,String>> unableList = new ArrayList<>();
        if(list!=null && list.size()>0){
            Map title = list.get(0);
            if(title.size()!=6 || !"商品id(必填)".equals(title.get("0")) || !"规格id(必填)".equals(title.get("1"))  || !"商品名称".equals(title.get("2")) ||
               !"规格".equals(title.get("3")) || !"调整后价格(元,必填)".equals(title.get("4"))  || !"调整后库存(件,必填)".equals(title.get("5"))
            ){
                throw GlobalException.build("导入表格格式错误，与导入模板不符");
            }
            list.remove(0);
            for(Map<String,String> goods : list){
                Map goodsNew = new HashMap();
                goodsNew.put("goodsId",goods.get("0"));
                goodsNew.put("skuId",goods.get("1"));
                goodsNew.put("goodsName",goods.get("2"));
                goodsNew.put("skuValue",goods.get("3"));
                goodsNew.put("moneyAmount",goods.get("4"));
                goodsNew.put("goodsCount",goods.get("5"));
                goodsNew.put("orgId",orgId);
                goodsNew.put("adminId",adminId);
                if(StringUtils.isEmpty(goodsNew.get("goodsId")) || StringUtils.isEmpty(goodsNew.get("skuId")) ||
                StringUtils.isEmpty(goodsNew.get("moneyAmount")) || StringUtils.isEmpty(goodsNew.get("goodsCount"))){
                    goodsNew.put("reason","缺失必填字段");
                    unableList.add(goodsNew);
                    continue;
                }
                String goodsIdS = goodsNew.get("goodsId").toString();
                String moneyAmountS = goodsNew.get("moneyAmount").toString();
                String goodsCountS = goodsNew.get("goodsCount").toString();
                moneyAmountS = moneyAmountS.replace(",","");
                if(!this.isNumericzidai(moneyAmountS) || Double.valueOf(moneyAmountS)>9999999.99 ||  Double.valueOf(moneyAmountS)<0){
                    goodsNew.put("reason","价格格式错误");
                    unableList.add(goodsNew);
                    continue;
                }
                if(!this.isNumer(goodsIdS)){
                    goodsNew.put("reason","商品ID格式错误");
                    unableList.add(goodsNew);
                    continue;
                }
                if(!this.isNumer(goodsCountS) || Long.valueOf(goodsCountS)>10000000 || Long.valueOf(goodsCountS)<0){
                    goodsNew.put("reason","库存格式错误");
                    unableList.add(goodsNew);
                    continue;
                }
                if(goodsNew.get("skuId").toString().startsWith("g")){
                    goodsNew.remove("skuId");
                }
                //获取商品详情
                Map<String, Object> oldGoods = shopGoodsService.getImportGoods(goodsNew);
                if(StringUtils.isEmpty(goodsNew.get("skuId"))){
                    goodsNew.put("skuId","g"+goodsNew.get("goodsId"));
                }
                if(oldGoods!=null && oldGoods.size()>0){
                    String moneyAmountOldS = oldGoods.get("moneyAmount").toString();
                    String memberAmountOldS = oldGoods.get("memberAmount").toString();
                    String mallsAmountMinS = oldGoods.get("mallsAmountMin").toString();
                    String mallsAmountMaxS = oldGoods.get("mallsAmountMax").toString();
                    String originalCostS = oldGoods.get("originalCost").toString();
                    Double moneyAmountEnd = Double.valueOf(moneyAmountS);
                    Double moneyAmountOld = Double.valueOf(moneyAmountOldS);
                    Double memberAmountOld = Double.valueOf(memberAmountOldS);
                    Double mallsAmountMin = Double.valueOf(mallsAmountMinS);
                    Double mallsAmountMax = Double.valueOf(mallsAmountMaxS);
                    Double originalCost = Double.valueOf(originalCostS);
                    if(moneyAmountEnd<=memberAmountOld || moneyAmountEnd<mallsAmountMin || (mallsAmountMax>0 && moneyAmountEnd>mallsAmountMax)
                    || (originalCost>0 && moneyAmountEnd>=originalCost)){
                        // 修改后价格小于会员价或者建议零售价最小值  或者大于建议零售价最大值
                        if(moneyAmountEnd<=memberAmountOld){
                            goodsNew.put("reason","修改后价格小于会员价");
                        }
                        if(moneyAmountEnd<mallsAmountMin){
                            goodsNew.put("reason","修改后价格小于建议零售价最小值");
                        }
                        if(mallsAmountMax>0 && moneyAmountEnd>mallsAmountMax){
                            goodsNew.put("reason","修改后价格大于建议零售价最大值");
                        }
                        if(originalCost>0 && moneyAmountEnd>=originalCost){
                            goodsNew.put("reason","修改后价格大于等于划线价");
                        }
                        unableList.add(goodsNew);
                        continue;
                    }
                    try {
                        oldGoods.put("moneyAmount",moneyAmountEnd);
                        this.checkGoodsRewetting(oldGoods,request);
                    }catch (Exception e){
                        goodsNew.put("reason","修改后商品亏损");
                        unableList.add(goodsNew);
                        continue;
                    }
                    goodsNew.put("skuValue",oldGoods.get("skuValue"));
                    goodsNew.put("goodsCountOld",oldGoods.get("goodsCount"));
                    goodsNew.put("goodsCover",oldGoods.get("goodsCover"));
                    goodsNew.put("goodsName",oldGoods.get("goodsName"));
                    goodsNew.put("moneyAmount",String.format("%.2f", moneyAmountOld));
                    goodsNew.put("mallsAmountMin",String.format("%.2f", mallsAmountMin));
                    goodsNew.put("mallsAmountMax",String.format("%.2f", mallsAmountMax));
                    goodsNew.put("moneyAmountEnd",String.format("%.2f", moneyAmountEnd));
                    Double difAmount = moneyAmountEnd - moneyAmountOld;
                    String f = "+";
                    if(difAmount<=0){
                        f = "";
                    }
                    goodsNew.put("difAmount",f+String.format("%.2f", difAmount));
                    Double difRatio = ((moneyAmountEnd-moneyAmountOld)/moneyAmountOld)*100;
                    String d = "+";
                    if(difRatio<=0){
                       d = "";
                    }
                    goodsNew.put("difRatio",d+String.format("%.2f",difRatio )+"%");
                    ableList.add(goodsNew);
                }else {
                    goodsNew.put("reason","商品不存在或非自有商品");
                    unableList.add(goodsNew);
                }
            }
        }
        String importId = UUID.randomUUID().toString();
        Map res = new HashMap();
        res.put("importId",importId);
        res.put("ableList",ableList);
        res.put("unableList",unableList);
        res.put("ableCount",ableList.size());
        res.put("unableCount",unableList.size());
        stringRedisTemplate.opsForValue().set("importExcel:"+importId, JSON.toJSONString(res),1, TimeUnit.DAYS);
        return res;
    }

    public boolean isNumericzidai(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]{0,2}");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }



    /**
     * 导出修改商品模板
     * @param response
     */
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response){
        List<Map<String,Object>> goodsList = new ArrayList();
        String fileName = "商品导入数据模板";
        shopGoodsService.exportTemplate(fileName,goodsList,response);
    }

    /**
     * 导出错误记录
     * @param importId
     * @param response
     */
    @GetMapping("/exportErrorTemplate")
    public void exportErrorTemplate(String importId,HttpServletResponse response){
        String  importMapString= stringRedisTemplate.opsForValue().get("importExcel:"+importId);
        Map<String,Object> importMap = (Map<String, Object>) parse(importMapString);
        if(importMap!=null && !StringUtils.isEmpty(importMap.get("unableList"))){
            List<Map<String, Object>> goodsList = (List<Map<String, Object>>) parse(importMap.get("unableList").toString());
            String fileName = "商品错误数据";
            shopGoodsService.exportTemplateError(fileName,goodsList,response);
        }
    }

    /**
     * 批量修改商品
     * @param request
     * @param params
     */
    @PostMapping("/updateGoodsList")
    public void updateGoodsList(@RequestBody Map<String, Object> params,  HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId",userinfo.getOrgId());
        if(userinfo.getSaler()){
            params.put("operatorId",userinfo.getCustomerId());
        }else {
            params.put("operatorId",userinfo.getOrgId());
        }
        params.put("operatorName",userinfo.getAdminName());
        shopGoodsService.updateGoodsList(params,userinfo);
    }

    /**
     * 获取修改记录
     * @param request
     * @param pageIndex
     * @param pageSize
     */
    @GetMapping("/getImportList")
    public PageInfo<Map<String,Object>> getImportList( int pageIndex, int pageSize,HttpServletRequest request){
        Map<String, Object> params =  new HashMap<>();
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId",userinfo.getOrgId());
        if(userinfo.getSaler()){
            params.put("operatorId",userinfo.getCustomerId());
        }else {
            params.put("operatorId",userinfo.getOrgId());
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(shopGoodsService.getImportList(params));
    }

    /**
     * 获取修改商品记录
     * @param pageIndex
     * @param pageSize
     * @param importId
     */
    @GetMapping("/getImportGoodsList")
    public PageInfo<Map<String,Object>> getImportGoodsList( int pageIndex, int pageSize,String importId,Integer status){
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(shopGoodsService.getImportGoodsList(importId,status));
    }
}
